package cn.edu.lcu.cs.javateaching.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 文件拷贝演示
 * 
 * @author Ling
 *
 */
public class FileCopy {
	private final static String FILE_SRC = "D:\\ABC.TXT";
	private final static String FILE_DST = "D:\\CBA.TXT";

	public static void main(String[] args) {
		initFile();
		copyFileWithBuffer();
//		copyFile();
	}

	/**
	 * 初始化源文件
	 */
	private static void initFile() {
		FileOutputStream outs = null;
		try {
			outs = new FileOutputStream(FILE_SRC);
			outs.write('a');
			outs.write('b');
			outs.write('c');
			outs.write('1');
			outs.write('2');
			outs.write('3');
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 采用传统的try-catch语句处理异常、关闭流
			// 语法烦琐
			try {
				outs.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 带缓冲的文件拷贝
	 */
	private static void copyFileWithBuffer() {
		// 使用try-with-resources语句声明并初始化流对象
		// IO流都实现了AutoCloseable接口，可以被try-with-resources语句自动关闭
		// 程序员不必手动关闭流，语法简洁
		try (FileInputStream ins = new FileInputStream(FILE_SRC);
				FileOutputStream outs = new FileOutputStream(FILE_DST)) {
			// 读写缓冲区
			byte[] buffer = new byte[1024];
			int length;
			while ((length = ins.read(buffer)) != -1) {
				outs.write(buffer, 0, length);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 拷贝文件
	 */
	private static void copyFile() {
		// 使用try-with-resources语句声明并初始化流对象
		// IO流都实现了AutoCloseable接口，可以被try-with-resources语句自动关闭
		// 程序员不必手动关闭流，语法简洁
		try (FileInputStream ins = new FileInputStream(FILE_SRC);
				FileOutputStream outs = new FileOutputStream(FILE_DST)) {
			int b;
			while ((b = ins.read()) != -1) {
				outs.write(b);
				System.out.println((char) b);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
